<template>
	<view class="page-main">
		<view class="form-box">
			<u--form ref="uForm" labelPosition="left" labelWidth="auto" :model="userForm" :rules="rules">
				<u-form-item label="头像" prop="avatar" borderBottom>
					<button class="images_but" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<u--image :src="userForm.avatar||'avatar'" radius="16rpx" width="120rpx" height="120rpx">
							<view slot="error" style="font-size: 16rpx;">请选择</view>
						</u--image>
					</button>
				</u-form-item>
				<u-form-item label="昵称" prop="nickname" borderBottom>
					<u--input v-model="userForm.nickname" type="nickname" placeholder="请填写" inputAlign="right"
						border="none" @blur="onNickNameInputBlur" />
				</u-form-item>
				<u-form-item label="性别" prop="sex" @click="isEdit?'':showGender = true" borderBottom>
					<u--input :value="userForm.sex === 1 ? '男':'女'" placeholder="请选择" inputAlign="right" border="none"
						disabled disabledColor="transparent" />
					<u-icon slot="right" name="arrow-right" />
				</u-form-item>
				<u-form-item label="生日" prop="birthYear" @click="showPicker = true" borderBottom>
					<u--input v-model="userForm.birthYear" placeholder="请选择" inputAlign="right" border="none" disabled
						disabledColor="#transparent" />
					<u-icon slot="right" name="arrow-right" />
				</u-form-item>
				<u-form-item label="手机号" prop="phone" borderBottom>
					<u--input v-model="userForm.phone" type="phone" placeholder="请填写" inputAlign="right"
						border="none" />
				</u-form-item>
				<u-form-item label="邮箱" prop="email">
					<u--input v-model="userForm.email" type="email" placeholder="请填写" inputAlign="right"
						border="none" />
				</u-form-item>
			</u--form>
		</view>

		<view style="margin-top: 80rpx;">
			<u-button type="success" shape="circle" @click="onSubmit">保存</u-button>
		</view>
		<view style="margin-top: 30rpx;">
			<u-button type="error" shape="circle" @click="onLogout">退出登录</u-button>
		</view>

		<u-action-sheet :show="showGender" :actions="actions" title="请选择性别" cancelText="取消" @close="showGender = false"
			@select="genderSelect" />

		<u-datetime-picker ref="datetimePicker" :show="showPicker" :value="newDate" :formatter="formatter" title="选择生日"
			mode="date" closeOnClickOverlay :minDate="minDate" :maxDate="newDate" @close="showPicker=false"
			@cancel="showPicker=false" @confirm="pickerConfirm" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isEdit: false,
				showGender: false,
				showPicker: false,
				minDate: new Date("1971").getTime(),
				newDate: new Date().getTime(),
				actions: [{
					name: '男',
					value: 1
				}, {
					name: '女',
					value: 0
				}, ],
				userForm: {},
				newAvatar: "",
				rules: {
					avatar: {
						required: true,
						message: '请上传头像',
						trigger: ['blur', 'change']
					},
					nickname: {
						type: 'string',
						required: true,
						message: '请输入昵称',
						trigger: ['blur']
					},
					sex: {
						validator: (rule, value, callback) => {
							if (value >= 0) {
								return true;
							}
							return false;
						},
						message: '请选择性别',
						trigger: ['blur', 'change']
					},
					birthYear: {
						type: 'string',
						required: true,
						message: '请选择生日',
						trigger: ['blur', 'change']
					},
					phone: {
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							if (value) {
								return uni.$u.test.mobile(value);
							}
							return true
						},
						message: '手机号码不正确',
						trigger: ['blur']
					},
					email: {
						type: 'email',
						message: '邮箱格式不正确',
						trigger: ['blur']
					}
				},
			}
		},
		onLoad(option) {
			this.userForm = {
				...this.vuex_user
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
			this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		methods: {
			onNickNameInputBlur(value) {
				this.userForm.nickname = value;
				this.$nextTick(() => this.$refs.uForm.validateField('nickname'))
			},
			onChooseAvatar(e) {
				this.newAvatar = e.detail.avatarUrl
				this.userForm.avatar = this.newAvatar
				this.$nextTick(() => this.$refs.uForm.validateField('avatar'))
			},
			onSubmit() {
				this.$refs.uForm.validate()?.then(async () => {
					uni.showLoading({
						title: '提交中...',
						mask: true
					});

					let form = this.userForm
					if (this.newAvatar) {
						//上传图片
						let fileRes = await this.$http.uploadFile('/resourceManage/fileUpload', this.newAvatar)
						if (fileRes.code !== 200) {
							uni.hideLoading();
							uni.$u.toast('图片上传失败')
							return
						}
						form.avatar = fileRes.data.resourcePath
					}
					// 更新用户信息
					form.id = this.vuex_user.id
					let res = await this.$http.post('/user/updateById', form)
					uni.hideLoading();
					if (res.code === 200) {

						this.$tools.vuex('vuex_user', form)
						uni.$u.toast('保存成功')
						if (getCurrentPages().length > 1) {
							uni.navigateBack();
						} else {
							uni.switchTab({
								url: '/pages/home/home'
							});
						}
						return
					}
					uni.$u.toast(res.message)
				}).catch((err) => {
					uni.hideLoading();
					if(err.message){
						uni.$u.toast(err.message)
						return
					}
					uni.$u.toast(err[0].message)
				})
			},
			genderSelect(e) {
				this.userForm.sex = e.value
			},
			pickerConfirm(e) {
				this.userForm.birthYear = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.showPicker = false;
			},
			onLogout() {
				this.$tools.logout()
				uni.navigateBack()
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				} else if (type === 'month') {
					return `${value}月`
				} else if (type === 'day') {
					return `${value}日`
				}
				return value
			},
		}
	}
</script>

<style>
	.form-box {
		padding: 20rpx 30rpx;
		border-radius: 20rpx;
		background-color: rgba(255, 255, 255, 0.85);
	}

	.images_but {
		margin-right: 0;
		background-color: transparent;
		padding-left: 0px;
		padding-right: 0px;
	}

	.images_but::after {
		border: none;
	}
</style>